import { AddPostionParam, AddTypeParam, EditPositionParam, EditTypeParam, GetPositionParam, GetTypeParam, PositionDetailListType, PositionDetailParam, PositionListType, PostionMemberParam, TypeListType } from "@Tea/model"
import { InitSelectWhereType, renderDelParam, renderDelSql, renderInsertParam, renderInsertSql, renderSelectSql, renderUpdateParam, renderUpdateSql } from "../utils/renderSql"
import promisePool from "./index"
import { DataAndTotal, SelectReturn } from "../types"
import { renderSelectParam } from "../utils/renderSql"
import { OkPacket, ResultSetHeader } from "mysql2"
import { ReposBase } from "./RepoBase"

export class TypeRepository extends ReposBase {
  public static inst = new TypeRepository()
  public static getInstance() {
    return TypeRepository.inst
  }

  getTypeList(params: GetTypeParam) {
    const sql = renderSelectSql({
      returnFeild: [
        { name: 'type_code', aliasName: "typeCode" },
        { name: 'type_name', aliasName: "typeName" },
        { name:'type_id',aliasName:"typeId"}
      ],
      database: [{ name: "tea_types" }],
      like: (() => {
        const wheres:InitSelectWhereType[] = []

        params.typeCode && wheres.push({ key: 'type_code', sqlVal: params.typeCode })
        params.typeName && wheres.push({ key: 'type_name',  sqlVal: params.typeName })

        return wheres
      })()
    })
    
    return this.query<PositionListType>(sql)
  }

  async addType(params: AddTypeParam){
    const insert: renderInsertParam = {
      database: 'tea_types',
      keyAndVal: [
        { key: "type_code", value: params.typeCode },
        { key: "type_name", value: params.typeName }
      ]
    }
    return this.insert(renderInsertSql(insert))
  }

   editType(params: EditTypeParam) { 
    const update: renderUpdateParam = {
      database: 'tea_types',
      keyAndVal:[
        { key: "type_code", value: params.typeCode },
        { key: "type_name", value: params.typeName }
      ],
      where: [
        { key: 'type_id', sqlVal: params.typeId }
      ]
    }
    const sql = renderUpdateSql(update)
    console.log("showSql:", sql);
    
    return this.update(sql)
  }
  
  delType(typeId: TypeListType['typeId']) {
    const del: renderDelParam = {
      database: "tea_types",
      keyAndVal: [
        { key: "type_id", sqlVal: typeId }
      ]
    }

    return this.delete(renderDelSql(del))
  }
}